//
//  PersonInfoVC.swift
//  BaseSwift
//
//  Created by gh on 2019/10/9.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit
import TZImagePickerController

class PersonInfoVC: UIViewController {

    let bgScr = UIScrollView()
    let iconBtn = UIButton()
    var tfs:Array<UITextField> = Array()
    var iconUrl:String = SPUtil.init().headImg ?? ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.navigationView.setTitle("个人资料")
        self.view.backgroundColor = UIColor.backgroundColor
        view.addSubview(self.bgScr)
        let _ = bgScr.sd_layout()?.spaceToSuperView(UIEdgeInsets(top: HT_StatusBarAndNavigationBarHeight+16, left: 0, bottom: HT_TabbarSafeBottomMargin, right: 0))
        
        self.navigationView.addRightButton(withTitle: "保存") { (view) in
            
            
            self.saveInfo()
            
        }
        
        let containerView = UIView()
        bgScr.addSubview(containerView)
        containerView.backgroundColor = UIColor.backgroundColor
        var temp = Array<UIView>()
        let tits = ["个人头像","手机号","昵称","性别","生日"]
        let places = ["手机号","给自己取个好名字吧","请选择","请选择"]
        
        for index in 0 ..< tits.count {
            
            let item = tits[index]
            let menuBtn = UIButton()
            menuBtn.tag = 10086+index
            menuBtn.backgroundColor = UIColor.white
            menuBtn.setTitle(item, for: .normal)
            menuBtn.titleLabel?.font = UIFont.commonFont
            menuBtn.titleLabel?.textAlignment = .center
            menuBtn.setTitleColor(UIColor.textTitleColor, for: .normal)
            menuBtn.setImage(UIImage(named: "向右"), for: .normal)
            menuBtn.addTarget(self, action: #selector(maskClick), for: .touchUpInside)
            containerView.addSubview(menuBtn)
            if item == "个人头像" {
                
                let _ = menuBtn.sd_layout()?.heightIs(80)
                
                iconBtn.addTarget(self, action: #selector(iconClick), for: .touchUpInside)
                menuBtn.addSubview(iconBtn)
                let _ = iconBtn.sd_layout()?.widthIs(50)?.heightIs(50)?.centerYEqualToView(menuBtn)?.rightSpaceToView(menuBtn,32)
                iconBtn.sd_cornerRadius = 25
                iconBtn.setImage(UIImage(named: "默认头像"), for: .normal)
                
                if SPUtil.init().headImg.count > 0{
                    
                    iconBtn.sd_setImage(with: URL(string: SPUtil.init().headImg ?? ""), for: .normal) { (A, B, C, D) in
                        
                        
                    }
                }

                

            }else{
                
                let _ = menuBtn.sd_layout()?.heightIs(50)
                let tf = UITextField()
                if index == 2{
                    
                    tf.text = SPUtil.init().nickName

                    
                }else{
                    
                    tf.isEnabled = false
                    if index == 1 {
                        
                        tf.text = SPUtil.init().mobile
                        menuBtn.setImage(UIImage(), for: .normal)

                    }
                    if index == 3 {
                        
                        tf.text = SPUtil.init().sex
                    }
                    if index == 4 {
                        
                        tf.text = SPUtil.init().birthDay
                    }

                }
                menuBtn.addSubview(tf)
                tf.textAlignment = .right
                tf.placeholder = places[index-1]
                tf.font = UIFont.commonFont
                
                tf.textColor = UIColor.textTitleColorBlack
                let _ = tf.sd_layout()?.heightIs(35)!.rightSpaceToView(menuBtn,32)!.centerYEqualToView(menuBtn)!.leftSpaceToView(menuBtn,95)
                tfs.append(tf)
                

            }
            
            let _ = menuBtn.titleLabel?.sd_layout()?.leftSpaceToView(menuBtn,16)
            menuBtn.titleLabel?.textAlignment = .left
            let _ = menuBtn.imageView?.sd_layout()?.widthIs(16)?.heightIs(16)?.centerYEqualToView(menuBtn)!.rightSpaceToView(menuBtn,16)
            
            
            temp.append(menuBtn)
            
        }
        let _ = containerView.sd_layout()?.topSpaceToView(bgScr,0)?.widthRatioToView(bgScr,1)
        
        containerView.setupAutoWidthFlowItems(temp, withPerRowItemsCount: 1, verticalMargin: 1, horizontalMargin: 0, verticalEdgeInset: 0, horizontalEdgeInset: 0)
        
    }
    
    @objc func maskClick(btn:UIButton){
        
        if btn.tag == 10089 {
            
            BRStringPickerView.showStringPicker(withTitle: "性别", dataSource: ["男","女"], defaultSelValue: "男", isAutoSelect: false, themeColor: UIColor.btnMainColor) { (str) in
                
                let tf = self.tfs[2]
                tf.text = (str as! String)
            }
        }else if btn.tag == 10090{
            

            
            BRDatePickerView.showDatePicker(withTitle: "请选择出生日期", dateType: .YMD, defaultSelValue:"" ) { (date) in
                
                let tf = self.tfs[3]
                tf.text = date 
            }
        }
        
        
    }
    func saveInfo(){
        
        let nicktf = tfs[1]
        let sextf = tfs[2]
        let birtf = tfs[3]

        var sex = ""
        if sextf.text == "男" {
            
            sex = "1"
        }else if sextf.text == "女"{
            
            sex = "2"
        }

        
        API.modifyPersonInfo(params: ["headImg":self.iconUrl,
                                      "nickName":nicktf.text ?? "",
                                      "sex":sex,
                                      "birthStringDay":birtf.text ?? ""]) { (result) in
            
            
            
            ToastUtil.show(msg: "修改成功")
                                        SPUtil.init().nickName = nicktf.text
                                        SPUtil.init().sex = sextf.text
                                        SPUtil.init().birthDay = birtf.text
                                        
            
        }
        
    }
    @objc func iconClick(){
        
        
        let pickCtrl = TZImagePickerController(maxImagesCount: 1, columnNumber: 6, delegate: nil, pushPhotoPickerVc: true)
        pickCtrl?.allowCrop = true
        pickCtrl?.needCircleCrop = true
        pickCtrl?.circleCropRadius = 160
        pickCtrl?.didFinishPickingPhotosHandle = {(photos,assets,isOriginalPhoto) in
            
            
            let str0 = NSDate.br_getString(Date(), format: "yyyyMMddHHmmss")
            let str1 = (arc4random()%100000+1).description
            let str2 = String(format: "%@%@", str0!,str1).toBase64()
            
            SVProgressHUD.show()
            SVProgressHUD.setDefaultStyle(.dark)
            SVProgressHUD.setDefaultAnimationType(.flat)
            

            BZHttpFileHelper.fileHelperShareInstance().uploadAmr((photos?.last?.jpegData(compressionQuality: 1.0))!, amrName: str2!+".png") { (result) in
                
                
                print("fullpath:\(result)")
                self.iconUrl = (result as! String)

                DispatchQueue.main.async(execute: {

                    self.iconBtn.setImage(photos?.last, for: .normal)

                    SVProgressHUD.dismiss()
                    API.modifyPersonInfo(params: ["headImg":self.iconUrl]) { (result) in
                        
                        
                        
                        SPUtil.init().headImg = self.iconUrl

                                                    
                        
                    }
                })
            }

        }
        self.present(pickCtrl!, animated: true) {
            
            
        }
       
    }



}
